import type { Router } from 'vue-router'
import { useRoutesStore } from '/@/store/modules/routes.ts'
import { authentication, loginInterception, routesWhiteList, supportVisit } from '/@lib/config'
import { toLoginRoute } from '/@lib/utils/routes.ts'
import { useAuthStore } from '/@/store/modules/auth.ts'

export function setupPermissionsGuard(router: Router) {
  router.beforeEach(async (to, _, next) => {
    const { routes, setRoutes } = useRoutesStore()
    const { token, getUserInfo, setVirtualRoles, resetAll } = useAuthStore()

    let hasToken = token
    if (!loginInterception) hasToken = true

    if (hasToken) {
      if (routes.length) {
        // 禁止已登录用户返回登录页
        if (to.path === '/login') {
          next({ path: '/' })
        } else next()
      } else {
        try {
          if (loginInterception) await getUserInfo()
          // config/setting.config.js loginInterception为false(关闭登录拦截时)时，创建虚拟角色
          else await setVirtualRoles()
          // 根据路由模式获取路由并根据权限过滤
          await setRoutes(authentication)
          next({ ...to, replace: true })
        } catch (err) {
          console.error('Router错误拦截:', err)
          await resetAll()
          next(toLoginRoute(to.fullPath))
        }
      }
    } else {
      if (routesWhiteList.includes(to.path)) {
        // 设置游客路由(不需要可以删除)
        if (supportVisit && !routes.length) {
          await setRoutes('visit')
          next({ path: to.path, replace: true })
        } else next()
      } else {
        next(toLoginRoute(to.fullPath))
      }
    }
  })
}
